package com.hunau.iot.server.nettyserver;

import com.hunau.iot.server.common.excention.FrameHeardExcetion;
import com.hunau.iot.server.common.inboundhandler.MySimpleChannelInboundHandler;
import com.hunau.iot.server.common.persist.BaseMo;
import com.hunau.iot.server.common.persist.spi.ServiceLoadException;
import com.hunau.iot.server.common.persist.spi.ServiceSupport;
import com.hunau.system.domain.TbEnergy;
import com.hunau.system.domain.TbEnvironment;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @program: ruoyi
 * @description:  环境与能源终端的数据解析获取
 * @author: Mr.Liu
 * @create: 2020-03-20 20:25
 **/
public class CheckHandler extends MySimpleChannelInboundHandler<String> {
    private static final Logger logger = LoggerFactory.getLogger(CheckHandler.class);
    private static BaseMo baseMo;
    static {
        try{
            baseMo = ServiceSupport.load(BaseMo.class);
        }catch (Throwable e){
            if(e instanceof ServiceLoadException){
                logger.error("com.hunau.iot.server.common.persist.BaseMo.class 未找到实现类",e);
            }
        }
    }

    protected CheckHandler(boolean autoRelease) {
        super(autoRelease);
    }


    @Override
    protected void messageRead(ChannelHandlerContext ctx, String s) throws Exception {

        String[] list = s.split(",");

        if(!"AA".equals(list[0]) && !"aa".equals(list[0])){
            throw new FrameHeardExcetion("包头错误");
        }
        if(!"12".equals(list[1])){
            throw new FrameHeardExcetion("数据类型错误错误");
        }
        //02代表回传的是环境采集的回传参数
        if ("02".equals(list[2])){
            if (list.length!=17){
                throw new FrameHeardExcetion("环境采集终端上传的数据长度错误");
            }
            //不需要接收的话，直接返回，不做数据处理
            if(ChannelManage.dontIn.containsKey(list[3])){
                ByteBuf resp = Unpooled.copiedBuffer("AA,02,12,0,0,CC".getBytes());
                ctx.channel().writeAndFlush(resp);
                return;
            }
            TbEnvironment tbEnvironment = new TbEnvironment();
            tbEnvironment.setImei(list[3]);
            tbEnvironment.setAmbientTemp(Double.valueOf(list[4]));
            tbEnvironment.setAmbientHum(Double.valueOf(list[5]));
            tbEnvironment.setAmbientLight(Double.valueOf(list[6]));
            tbEnvironment.setCo2(Double.valueOf(list[7]));
            tbEnvironment.setSoilTemp(Double.valueOf(list[8]));
            tbEnvironment.setSoilHum(Double.valueOf(list[9]));
            tbEnvironment.setAtmoPressure(Double.valueOf(list[10]));
            tbEnvironment.setWindSpeed(Double.valueOf(list[11]));
            tbEnvironment.setWindDirection(list[12]);
            tbEnvironment.setSnowRain(list[13]);
            tbEnvironment.setPm25(Double.valueOf(list[14]));
            tbEnvironment.setCo(Double.valueOf(list[15]));
            tbEnvironment.setSo2(Double.valueOf(list[16]));
            tbEnvironment.setColltime(new Date());
            baseMo.insert(tbEnvironment);
            /**环境数据上传才返回响应数据给终端**/
            ByteBuf resp = Unpooled.copiedBuffer("AA,02,12,0,0,CC".getBytes());
            ctx.channel().writeAndFlush(resp);
        }
        //能源终端
        else if ("01".equals(list[2])){
            if (list.length!=13){
                throw new FrameHeardExcetion("能源终端上传的数据错误");
            }
            //不需要接收的话，直接返回，不做数据处理
            if(ChannelManage.dontIn.containsKey(ChannelManage.dev2id.get(ctx.channel().id().toString()))){
                ByteBuf resp = Unpooled.copiedBuffer("AA,02,12,0,0,CC".getBytes());
                ctx.channel().writeAndFlush(resp);
                return;
            }
            TbEnergy tbEnergy = new TbEnergy();
            tbEnergy.setImei(ChannelManage.dev2id.get(ctx.channel().id().toString()));
            tbEnergy.setPow1(Double.valueOf(list[3]));
            tbEnergy.setGrouppow(Double.valueOf(list[4]));
            tbEnergy.setVol18v1(Double.valueOf(list[5]));
            tbEnergy.setVol18v2(Double.valueOf(list[6]));
            tbEnergy.setVol24(Double.valueOf(list[7]));
            tbEnergy.setVol28(Double.valueOf(list[8]));
            tbEnergy.setExtendpow(Double.valueOf(list[9]));
            tbEnergy.setSolarpow(Double.valueOf(list[10]));
            tbEnergy.setCharge(list[11]);
            tbEnergy.setWork(Integer.parseInt(list[12]));
            baseMo.insert(tbEnergy);
        }else {
            throw new FrameHeardExcetion("未知终端类型数据");
        }
        //获取客户端ip
//        InetSocketAddress ipSocket = (InetSocketAddress)ctx.channel().remoteAddress();
//        String clientIp = ipSocket.getAddress().getHostAddress();
        //System.getProperty("line.separator") 这也是换行符,功能和"\n"是一致的,但是此种写法屏蔽了 Windows和Linux的区别 ，更保险一些


    }

    /**
     * channelRead()函数执行完之后执行
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx , Throwable cause){
        if (cause instanceof FrameHeardExcetion){
            logger.error(ctx.channel().id()+">>>发来的数据：\""+cause.getMessage()+"\"，关闭连接"+">>>"+HeartBeatServer.dataTime());
        }
        //应该发送响应码给客户端
        ctx.writeAndFlush(Unpooled.copiedBuffer("501".getBytes()));
        ctx.close();
    }
}
